<template>
  <div class="bg-gray-50 min-h-screen">
    <!-- 顶部导航栏 -->
    <header class="bg-white border-b border-gray-200 sticky top-0 z-50">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex items-center justify-between h-16">
          <!-- Logo和身份标识 -->
          <div class="flex items-center gap-3">
            <div class="flex items-center gap-2">
              <div class="w-10 h-10 bg-blue-600 rounded-lg overflow-hidden">
                <img src="../../../头像.jpg" alt="头像" class="w-full h-full object-cover" />
              </div>
              <span class="text-xl font-semibold text-gray-900">校园快递代拿</span>
            </div>
            <span class="px-2 py-1 bg-blue-100 text-blue-700 text-xs rounded">代拿员</span>
          </div>

          <!-- 右侧按钮 -->
          <HeaderActions />
        </div>
      </div>
    </header>

    <!-- 标签页导航 -->
    <nav class="bg-white border-b border-gray-200">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex gap-8">
          <button class="py-4 text-blue-600 border-b-2 border-blue-600 font-medium">接单大厅</button>
          <button class="py-4 text-gray-600 hover:text-gray-900 border-b-2 border-transparent hover:border-gray-300" @click="$router.push('/courier/orders')">我的订单</button>
          <button class="py-4 text-gray-600 hover:text-gray-900 border-b-2 border-transparent hover:border-gray-300" @click="$router.push('/courier/profile')">我的主页</button>
        </div>
      </div>
    </nav>

    <!-- 主要内容区域 -->
    <main class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <!-- 页面标题 -->
      <h1 class="text-2xl font-bold text-gray-900 mb-6">接单大厅</h1>

      <!-- 筛选栏 -->
      <div class="bg-white rounded-lg shadow-sm p-4 mb-6">
        <div class="flex flex-wrap items-center gap-6">
          <!-- 订单筛选 -->
          <div class="flex items-center gap-3">
            <span class="text-sm text-gray-600">筛选条件:</span>
            <div class="flex gap-2">
              <button @click="filterType = 'all'" :class="{'bg-blue-600 text-white': filterType === 'all', 'text-gray-600 hover:bg-gray-100': filterType !== 'all'}" class="px-3 py-1 text-sm rounded">全部订单</button>
              <button @click="filterType = 'price'" :class="{'bg-blue-600 text-white': filterType === 'price', 'text-gray-600 hover:bg-gray-100': filterType !== 'price'}" class="px-3 py-1 text-sm rounded">按价格排序</button>
              <button @click="filterType = 'distance'" :class="{'bg-blue-600 text-white': filterType === 'distance', 'text-gray-600 hover:bg-gray-100': filterType !== 'distance'}" class="px-3 py-1 text-sm rounded">距离最近</button>
              <button @click="filterType = 'smart'" :class="{'bg-blue-600 text-white': filterType === 'smart', 'text-gray-600 hover:bg-gray-100': filterType !== 'smart'}" class="px-3 py-1 text-sm rounded">智能推荐</button>
            </div>
          </div>

          <!-- 搜索框 -->
          <div class="flex-1 min-w-[200px]">
            <div class="relative">
              <input v-model="searchKeyword" type="text" placeholder="搜索订单号、物品信息" class="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
              <svg class="w-5 h-5 text-gray-400 absolute left-3 top-1/2 -translate-y-1/2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/>
              </svg>
            </div>
          </div>
        </div>
      </div>

      <!-- 订单列表 -->
      <div class="space-y-4">
        <div v-for="order in pagedOrders" :key="order.id" class="bg-white rounded-lg shadow-sm p-6">
          <!-- 订单头部 -->
          <div class="flex items-center justify-between mb-4">
            <div class="flex items-center gap-3">
              <span class="text-sm text-gray-600">订单编号: {{ order.id }}</span>
              <span class="px-2 py-1 text-xs rounded"
                    :class="order.statusText==='待接单' ? 'bg-yellow-100 text-yellow-700' : (order.statusText==='配送中' ? 'bg-blue-100 text-blue-700' : (order.statusText==='已完成' ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-600'))">
                {{ order.statusText || '待接单' }}
              </span>
            </div>
            <span class="text-sm text-gray-500">{{ order.time }}</span>
          </div>

          <!-- 订单内容 -->
          <div class="mb-4">
            <h3 class="text-lg font-semibold text-gray-900 mb-1">{{ order.title }}</h3>
          </div>

          <!-- 地址信息 -->
          <div class="grid md:grid-cols-2 gap-4 mb-4">
            <div class="flex items-start gap-2">
              <svg class="w-5 h-5 text-gray-400 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z"/>
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 11a3 3 0 11-6 0 3 3 0 016 0z"/>
              </svg>
              <div>
                <p class="text-sm text-gray-600">取件地点</p>
                <p class="text-sm font-medium text-gray-900">{{ order.pickupLocation }}</p>
              </div>
            </div>
            <div class="flex items-start gap-2">
              <svg class="w-5 h-5 text-gray-400 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6"/>
              </svg>
              <div>
                <p class="text-sm text-gray-600">送达地点</p>
                <p class="text-sm font-medium text-gray-900">{{ order.dropoffLocation }}</p>
              </div>
            </div>
          </div>

          <!-- 信誉信息 / 距离信息 -->
          <div class="mb-4">
            <!-- 下单者信用值 -->
            <div class="flex items-center gap-2 mb-2">
              <svg class="w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z"/>
              </svg>
              <p class="text-sm text-gray-600">下单者信用值: {{ order.rating }}</p>
            </div>

            <!-- 期望送达时间 -->
            <div class="flex items-start gap-2 mb-1">
              <svg class="w-5 h-5 text-gray-400 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"/>
              </svg>
              <p class="text-sm text-gray-600">期望送达时间：{{ order.expectedTime || '尽快送达' }}</p>
            </div>

            <!-- 距离信息：基于订单表 distance_m 字段 -->
            <div class="flex items-start gap-2 mb-1" v-if="order.distanceMeters != null">
              <svg class="w-5 h-5 text-gray-400 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 20l-5.447-2.724A2 2 0 013 15.382V5a2 2 0 012-2h5m4 0h5a2 2 0 012 2v10.382a2 2 0 01-1.553 1.894L15 20m-6-9l2.293-2.293a1 1 0 011.414 0L15 11"/>
              </svg>
              <p class="text-sm text-gray-600">距离约 {{ formatDistance(order.distanceMeters) }}</p>
            </div>

            <!-- 备注/物品描述/期望时间段，多行文本，每行一个小图标 -->
            <div v-if="order.noteLines && order.noteLines.length" class="space-y-0.5 mt-1">
              <div v-for="(line, idx) in order.noteLines" :key="idx" class="flex items-start gap-2">
                <svg class="w-5 h-5 text-gray-400 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m-7 4h8a2 2 0 002-2V6a2 2 0 00-2-2H9l-2 2H5a2 2 0 00-2 2v10a2 2 0 002 2z"/>
                </svg>
                <p class="text-sm text-gray-600">{{ line }}</p>
              </div>
            </div>
          </div>

          <!-- 订单底部 -->
          <div class="flex items-center justify-between pt-4 border-t border-gray-200">
            <div class="text-sm text-gray-600">订单金额</div>
            <div class="flex items-center gap-4">
              <span class="text-xl font-bold text-gray-900">¥{{ order.price }}</span>
              <button @click="acceptOrder(order.id)" class="px-4 py-2 text-sm bg-blue-600 text-white rounded hover:bg-blue-700">立即接单</button>
            </div>
          </div>
        </div>
      </div>

      <!-- 分页：与“我的订单”页相同逻辑 -->
      <div class="flex items-center justify-center gap-2 mt-8">
        <!-- 上一页 -->
        <button
          class="w-8 h-8 flex items-center justify-center rounded border border-gray-300 hover:bg-gray-100 disabled:opacity-40 disabled:hover:bg-white"
          :disabled="currentPage === 1"
          @click="currentPage > 1 && (currentPage -= 1)"
        >
          <svg class="w-5 h-5 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"/>
          </svg>
        </button>

        <!-- 中间页码：1 ~ totalPages -->
        <button
          v-for="p in totalPages"
          :key="p"
          class="w-8 h-8 flex items-center justify-center rounded border"
          :class="p === currentPage ? 'bg-blue-600 text-white border-blue-600' : 'border-gray-300 text-gray-600 hover:bg-gray-100'"
          @click="currentPage = p"
        >
          {{ p }}
        </button>

        <!-- 下一页 -->
        <button
          class="w-8 h-8 flex items-center justify-center rounded border border-gray-300 hover:bg-gray-100 disabled:opacity-40 disabled:hover:bg-white"
          :disabled="currentPage === totalPages"
          @click="currentPage < totalPages && (currentPage += 1)"
        >
          <svg class="w-5 h-5 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/>
          </svg>
        </button>
      </div>
    </main>
  </div>
</template>

<script>
import axios from 'axios'
import HeaderActions from '../components/HeaderActions.vue'
export default {
  name: 'CourierOrderHall',
  components: { HeaderActions },
  data() {
    return {
      filterType: 'all',
      searchKeyword: '',
      orders: [],
      currentPage: 1,
      pageSize: 10
    }
  },
  computed: {
    // 先根据搜索关键字和排序得到完整的可见订单列表
    filteredOrders() {
      let result = this.orders

      // 搜索过滤
      if (this.searchKeyword.trim()) {
        const keyword = this.searchKeyword.trim().toLowerCase()
        result = result.filter(order => {
          const idStr = String(order.id || '').toLowerCase()
          const titleStr = String(order.title || '').toLowerCase()
          const descStr = String(order.desc || '').toLowerCase()
          const pickupStr = String(order.pickupLocation || '').toLowerCase()
          const dropoffStr = String(order.dropoffLocation || '').toLowerCase()
          return (
            idStr.includes(keyword) ||
            titleStr.includes(keyword) ||
            descStr.includes(keyword) ||
            pickupStr.includes(keyword) ||
            dropoffStr.includes(keyword)
          )
        })
      }

      // 排序
      if (this.filterType === 'price') {
        result = [...result].sort((a, b) => parseFloat(b.price) - parseFloat(a.price))
      } else if (this.filterType === 'distance' || this.filterType === 'smart') {
        // 距离/智能推荐排序
        result = [...result].sort((a, b) => {
          // 如果有后端计算的 smart_score，智能推荐优先按分数从高到低
          if (this.filterType === 'smart') {
            const sa = typeof a.smartScore === 'number' ? a.smartScore : (a.smartScore != null ? Number(a.smartScore) : null)
            const sb = typeof b.smartScore === 'number' ? b.smartScore : (b.smartScore != null ? Number(b.smartScore) : null)
            if (sa != null && sb != null && !Number.isNaN(sa) && !Number.isNaN(sb) && sa !== sb) {
              return sb - sa
            }
          }

          // 回退到距离优先，其次价格
          const da = typeof a.distanceMeters === 'number' ? a.distanceMeters : Number.MAX_SAFE_INTEGER
          const db = typeof b.distanceMeters === 'number' ? b.distanceMeters : Number.MAX_SAFE_INTEGER
          if (da !== db) return da - db

          const pa = parseFloat(a.price)
          const pb = parseFloat(b.price)
          if (!Number.isNaN(pa) && !Number.isNaN(pb) && pa !== pb) return pb - pa
          return 0
        })
      }

      return result
    },
    // 总页数（基于过滤后的结果动态计算）
    totalPages() {
      const total = this.filteredOrders.length
      if (total === 0) return 1
      return Math.ceil(total / this.pageSize)
    },
    // 当前页要展示的订单列表
    pagedOrders() {
      const start = (this.currentPage - 1) * this.pageSize
      const end = start + this.pageSize
      return this.filteredOrders.slice(start, end)
    }
  },
  methods: {
    async fetchAvailable() {
      try {
        // 从后端读取待接单订单
        const token = localStorage.getItem('userToken')
        const courierId = localStorage.getItem('userId')
        const { data } = await axios.get('/api/orders/available', {
          headers: {
            Authorization: `Bearer ${token}`
          },
          params: {
            courierId: courierId ? Number(courierId) : undefined
          }
        })
        // 适配后端返回的数据结构：data.orders
        const list = (data && data.data && data.data.orders) || []
        const toText = (s) => (s===1||s==='1')?'待接单':(s===2||s==='2')?'配送中':(s===3||s==='3')?'已完成':(s===4||s==='4')?'已取消':(s||'待接单')
        this.orders = list.map(r => {
          const rawNote = r.note || ''
          const noteLines = String(rawNote)
            .split('\n')
            .map(s => s.trim())
            .filter(Boolean)
          return {
            id: r.id,
            title: '快递代拿',
            desc: rawNote,
            pickupLocation: r.pickup_location + (r.pickup_code ? ` • 取件码: ${r.pickup_code}` : ''),
            dropoffLocation: r.delivery_address,
            price: Number(r.fee || r.suggested_fee || 0).toFixed(2),
            rating: Number(r.orderer_credit || r.credit_score || r.rating || 0),
            time: (r.created_at || '').replace('T',' ').slice(0,19),
            expectedTime: (r.delivery_time || r.expected_time || '').replace('T',' ').slice(0,19),
            noteLines,
            distanceMeters: typeof r.distance_m === 'number' ? r.distance_m : (r.distance_m != null ? Number(r.distance_m) : null),
            smartScore: typeof r.smart_score === 'number' ? r.smart_score : (r.smart_score != null ? Number(r.smart_score) : null),
            statusText: toText(r.status)
          }
        })
      } catch (e) {
        console.error('获取可接订单失败', e)
        alert('获取可接订单失败，请稍后再试')
      }
    },
    async acceptOrder(orderId) {
      const courierId = localStorage.getItem('userId')
      if (!courierId) {
        alert('请先登录');
        this.$router.push('/login');
        return;
      }
      try {
        // 使用专用接单接口，后端会自动处理外键转换
        await axios.post(`/api/orders/${orderId}/accept`, { courier_user: Number(courierId) })
        alert('接单成功')
        // 跳转到我的订单查看
        this.$router.push('/courier/orders')
      } catch (e) {
        console.error('接单失败', e)
        alert('接单失败，请稍后再试')
      }
    },
    async contactOrderer(orderId) {
      const me = Number(localStorage.getItem('userId'))
      if (!me) { this.$router.push('/login'); return }
      try {
        // 读取订单详情以拿到下单者ID（order_user_id/order_user）
        const { data } = await axios.get(`/api/orders/${orderId}`)
        const d = (data && data.data) || {}
        const ordererId = Number(d.orderer_user_id || d.order_user_id || d.order_user || 0)
        if (!ordererId) { alert('无法获取下单者信息'); return }
        const { data: created } = await axios.post('/api/messages/conversations', {
          participants: [me, ordererId],
          order_id: Number(orderId),
          type: 1
        })
        const cid = created && created.data && created.data.id
        this.$router.push({ path: '/messages', query: { cid } })
      } catch (e) {
        console.error('联系下单者失败', e)
        alert('联系下单者失败，请稍后再试')
      }
    },
    formatDistance(m) {
      if (m == null || Number.isNaN(m)) return '未知'
      const val = Number(m)
      if (val < 1000) return `${Math.round(val)}米`
      return `${(val / 1000).toFixed(1)}公里`
    }
  },
  mounted() {
    this.fetchAvailable()
  }
}
</script>

